package com.liry.security.config;

import com.alibaba.fastjson.JSONArray;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;

/**
 * 自定义访问决策管理器
 * @author ALI
 * @since 2023/6/16
 */
public class CustomAccessDecisionManager implements AccessDecisionManager {

    private final CacheManager cacheManager;

    public CustomAccessDecisionManager(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
    throws AccessDeniedException, InsufficientAuthenticationException {
        // 获取认证信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authorities.isEmpty()) {
            throw new AccessDeniedException("无权限！");
        }
        // 获取权限信息
        Set<String> permissions = new HashSet<>();
        for (GrantedAuthority authority : authorities) {
            Object o = cacheManager.get(authority.getAuthority());
            if (o != null) {
                List<String> collect = JSONArray.parseArray(o.toString()).stream().map(Object::toString).collect(Collectors.toList());
                permissions.addAll(collect);
            }
        }
        if (permissions.isEmpty()) {
            throw new AccessDeniedException("无权限！");
        }
        FilterInvocation filterInvocation = (FilterInvocation) object;
        // 判断是否有权限访问
        String api = filterInvocation.getRequestUrl();
        if (!permissions.contains(api)) {
            throw new AccessDeniedException("无权限！");
        }
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
